package lab3.server;

import java.awt.EventQueue;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import javax.swing.JOptionPane;

import lab3.server.core.Server;

/**
 * Server application Entry. Very rude setup no interfaces
 * so we'll have cyclic dependencies.
 *
 * @author hajo
 * 
 * NOTE: Application needs a policy file in
 * project directory, see security.policy
 *
 *  SEE TODO BELOW!!!!
 */


public class Main {

   /**
    * @param
    * args[0] registry port
    * args[1] server port
    */
   public static void main(String[] args) {
      int registryPort = 0;
      int serverPort = 0;

      if (args.length != 2) {
         System.out.println("Must supply registry and server ports");
         System.exit(1);
      } else {
         try {
            registryPort = Integer.parseInt(args[0]);
            serverPort = Integer.parseInt(args[1]);
         } catch (NumberFormatException e) {
            System.out.println("Bad registry and/or server ports");
            System.exit(1);
         }
      }

      System.out.println("Trying to start server with registryport " + args[0]
            + " and server port " + args[1]);

      // Should have security manager when usign RMI
      SecurityManager sm = System.getSecurityManager();
      if (sm == null) {
         System.setSecurityManager(new SecurityManager());
      }
      try {
         /*
          * Create remote object
          */
         final Server server = new Server(registryPort, serverPort);
         /*
          * Export object and get at stub (i.e. a proxy for the server, 
          * see Proxy desing pattern
          */
         // TODO
         //IServer stub = (IServer) UnicastRemoteObject.exportObject(server,
         //      serverPort);
         /*
          * Create a registry
          */
         LocateRegistry.createRegistry(registryPort);
         Registry registry = LocateRegistry.getRegistry(registryPort);
         /*
          * Bind the stub in the registry
          */
         // TODO
         //registry.rebind(Constants.MB_SERVER_NAME, stub);
         System.out.println("Server stub bound in registry");

         EventQueue.invokeLater(new Runnable() {

            public void run() {
             // TODO
               JOptionPane.showMessageDialog(null, "Must create and implement IServer");
               //new MainFrame(server).setVisible(true);
            }
         });
      } catch (Exception e) {
         System.out.println("Server exception: " + e.getMessage());
         e.printStackTrace();
      }
   }
}
